package com.example.pei.ithinklearnt.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.adapter.NearbyPeopleAdapter;
import com.example.pei.ithinklearnt.adapter.NewCommentAdapter;
import com.example.pei.ithinklearnt.adapter.base.OnRecyclerViewListener;
import com.example.pei.ithinklearnt.bean.AlumniCircle;

import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.listener.QueryUserListener;
import com.example.pei.ithinklearnt.model.AlumniCircleModelImp;
import com.example.pei.ithinklearnt.model.UserModel;
import com.example.pei.ithinklearnt.utils.LocationUtil;
import com.example.pei.ithinklearnt.utils.ToastUtil;
import com.example.pei.ithinklearnt.view.base.BaseActivity;
import com.example.pei.ithinklearnt.view.base.IMutlipleItem;
import com.example.pei.ithinklearnt.view.customview.EmptyRecyclerView;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static cn.bmob.v3.Bmob.getApplicationContext;
import static com.example.pei.ithinklearnt.utils.BeanOperationUtil.putBean;
import static com.example.pei.ithinklearnt.utils.PermisionUtil.hasCoarseLocationPermission;

public class FindNearbyPeopleActivity extends BaseActivity {


    private KProgressHUD hud; //等待进度条

    private List<UserInfo> nearby;  //附近的人
    private NearbyPeopleAdapter adapter;

    @BindView(R.id.swipe_target)
    EmptyRecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;


    @OnClick(R.id.button_backward)
    void back(){
        finish();
    }
    @OnClick(R.id.tv_refresh)
    void refresh(){
        smartRefreshLayout.autoRefresh(0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_nearby_people);
        init();
        //开始读取权限状态，可以直接进行匹配最近的人
        hud = KProgressHUD.create(FindNearbyPeopleActivity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setDimAmount(0.4f)
                .setLabel("客官请稍等~~~")
                .setCornerRadius(10)
                .show();
        readPhoneStateTask();
    }


    private AMapLocationClient locationClientSingle = null;
    private static final int RC_COARSE_LOCATION_PERM = 124;





    /**
     * 启动单次客户端定位
     */
    void startSingleLocation(){
        if(null == locationClientSingle){
            locationClientSingle = new AMapLocationClient(getApplicationContext());
        }

        AMapLocationClientOption locationClientOption = new AMapLocationClientOption();
        //使用单次定位
        locationClientOption.setOnceLocation(true);
        // 地址信息
        locationClientOption.setNeedAddress(true);
        locationClientOption.setLocationCacheEnable(true);
        locationClientSingle.setLocationOption(locationClientOption);
        locationClientSingle.setLocationListener(locationSingleListener);
        locationClientSingle.startLocation();
    }
    /**
     * 单次客户端的定位监听
     */
    AMapLocationListener locationSingleListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            StringBuffer sb = new StringBuffer();
            sb.append("当前位置\n");
            if(null == location){
                sb.append("定位失败：location is null!!!!!!!");
            } else {
                sb.append(LocationUtil.getMyLocationStr(location));
                double longitude=location.getLongitude();//经度
                double latitude=location.getLatitude();  //纬度

                //更新用户的地理位置

                final UserInfo newUser = new UserInfo();
                newUser.setGpsLocate(new BmobGeoPoint(longitude, latitude));
                final UserInfo current=AppApplication.getCurrentUser();
                current.setGpsLocate(new BmobGeoPoint(longitude, latitude));
                AppApplication.setCurrentUser(current);
                newUser.update(current.getObjectId(),new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if(e==null){
                            //查询最近的十个人
                            BmobQuery<UserInfo> bmobQuery = new BmobQuery<>();
                            bmobQuery.addWhereNear("gpsLocate", newUser.getGpsLocate());
                            bmobQuery.addWhereNotEqualTo("username", current.getUsername()); //自己的不查
                            bmobQuery.setLimit(10);    //获取最接近用户地点的10条数据
                            bmobQuery.findObjects(new FindListener<UserInfo>() {
                                @Override
                                public void done(List<UserInfo> object, BmobException e) {
                                    hud.dismiss();
                                    smartRefreshLayout.finishRefresh();
                                    if(e==null){
                                        //toast("查询成功：共" + object.size() + "条数据。");
                                        //ToastUtil.ToastShow(getApplicationContext(),"已经查询到："+object.size()+"个最近的人",0);
                                        nearby=object;
                                        adapter.bindDatas(nearby);
                                    }else{
                                        ToastUtil.ToastShow(getApplicationContext(),"查询附近人失败：" + e.getMessage(),0);
                                    }
                                }
                            });
                        }else{
                            hud.dismiss();
                            smartRefreshLayout.finishRefresh();
                            ToastUtil.ToastShow(getApplicationContext(),"更新地理位置失败：" + e.getMessage(),0);
                        }
                    }
                });
            }
            // tvLocation.setText(sb.toString());
            stopSingleLocation();
        }
    };
    /**
     * 停止单次客户端
     */
    void stopSingleLocation(){
        if(null != locationClientSingle){
            locationClientSingle.stopLocation();
        }
    }

    //   @OnClick(R.id.btn_nearest)
    @AfterPermissionGranted(RC_COARSE_LOCATION_PERM)
    public void readPhoneStateTask() {
        if (hasCoarseLocationPermission(this)) {
            //如果有权限

            startSingleLocation();
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(
                    this,
                    "需要定位权限否则将无法使用此功能.",
                    RC_COARSE_LOCATION_PERM,
                    Manifest.permission.ACCESS_COARSE_LOCATION);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (hasCoarseLocationPermission(this)) {
            //如果有权限
            startSingleLocation();
        }
        // EasyPermissions handles the request result.
        //EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void init(){
        IMutlipleItem<UserInfo> mutlipleItem= new IMutlipleItem<UserInfo>() {
            @Override
            public int getItemLayoutId(int viewtype) {
                return R.layout.item_nearby_people;
            }

            @Override
            public int getItemViewType(int postion, UserInfo comment) {
                return 0;
            }

            @Override
            public int getItemCount(List<UserInfo> list) {
                return nearby!=null?nearby.size():0;
            }
        };
        adapter=new NearbyPeopleAdapter(this,mutlipleItem,null);
        adapter.setOnRecyclerViewListener(new OnRecyclerViewListener() {
            @Override
            public void onItemClick(View v, final int position) {

                Bundle bundle=new Bundle();
                bundle.putSerializable("u",adapter.getItem(position));
                Intent intent = new Intent();
                intent.setClass(FindNearbyPeopleActivity.this, UserInfoActivity0.class);
                intent.putExtra(FindNearbyPeopleActivity.this.getPackageName(), bundle);
                startActivity(intent);

            }


            @Override
            public boolean onItemLongClick(View v, int position) {
                return false;
            }
        });
        recyclerView.setAdapter(adapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                readPhoneStateTask();
            }
        });
    }


    @Override
    public void onDestroy() {
        if(null != locationClientSingle){
            locationClientSingle.onDestroy();
            locationClientSingle = null;
        }
        super.onDestroy();
    }

}
